import React, { useEffect, useState } from 'react'
import { NavBar, Space, Toast, Form, Input, Button, Picker } from 'antd-mobile'
import { useLocalStorageState, useRequest } from 'ahooks'
import { useNavigate, useSearchParams } from 'react-router-dom'


import PassInput from '../../components/PassInput'
import { reg } from '../../utils/validate'
import { loginApi } from '../../api/api'
import { UserInterFace } from '../../utils/types'
import { ShowErrorMsg, ShowMsg } from '../../utils/message'
import { useComment, useGoBackOrMine } from '../../hooks/common'




const LoginByName = () => {
  const router = useNavigate()
  const [form] = Form.useForm()
  const [query] = useSearchParams()
  const { GoBackOrMine } = useGoBackOrMine()
  // 登录成功后储存用户名
  const [AppName, setAppName] = useLocalStorageState<string | undefined>('AppName')

  // 登录成功后储存 token
  const [AppToken, setAppToken] = useLocalStorageState<string | undefined>('AppToken')

  // 登录 写法1
  // const onFinish = async (value: UserInterFace) => {
  //   const res: any = await loginApi(value)
  //   if (res.code == 200) {
  //     ShowMsg('登录成功')
  //     setAppName(value.username)
  //     setAppToken(res.token)
  //   } else {
  //     ShowErrorMsg(res.msg)
  //   }
  // }


  // 登录 写法2
  const { loading, run } = useRequest(loginApi, {
    manual: true, // 手动触发
    onSuccess: (res: any, params: any) => {
      if (res.code == 200) {
        console.log(res);
        console.log(params);
        ShowMsg('登录成功')
        // router('/main/mine')
        GoBackOrMine()
        setAppName(params[0].username)
        setAppToken(res.token)
      } else {
        ShowErrorMsg(res.msg)
      }
    }
  })

  const onFinish = (value: UserInterFace) => {
    run(value)
  }

  useEffect(() => {
    if (query.get('username')) {
      form.setFieldValue('username', query.get('username'))
    } else {
      form.setFieldValue('username', AppName)
    }
  }, [])

  return (
    <div>
      <Form layout='horizontal' mode='card' form={form} onFinish={onFinish}>
        <Form.Header>请输入用户名，密码以登录</Form.Header>
        <Form.Item
          label='用户名：'
          name='username'
          rules={[{ required: true, message: '用户名不能为空' }]}
        >
          <Input placeholder='请输入用户名' clearable />
        </Form.Item>


        <PassInput dependencies={['dbpass']}></PassInput>


        <div>
          <Button color="success" className='mt20' block type="submit" >登 录</Button>
        </div>

        <div style={{ marginTop: '30px', display: 'flex', justifyContent: 'space-around' }}>
          <Button color='primary' fill='none' onClick={() => router('/reg')}>
            没有账号？去注册
          </Button>
          <Button color='primary' fill='none' style={{ marginLeft: '87px', fontSize: '14px', color: 'orange' }} onClick={() => router('/findpass')}>
            忘记密码
          </Button>
        </div>
      </Form>
    </div>
  )
}

export default LoginByName
